"""
"""
import unittest as ut
import sys
import tempfile

import basicVdsTest as vdst

sys.path.append("../../")
import storage.nfs as nfs
from storage.storage_connection import StorageServerConnection

class NfsMountingRace(vdst.BasicVDSTest):
    #For convenience. I didn't put it in the base class because I didn't want to commit.
    mycfg = property(lambda self: self.cfg[self.__class__.__name__])

    @classmethod
    def getConfigTemplate(cls):
        return { cls.__name__ : {
                "NfsMount1" : {"default" : "server:/export/"}
            }
        }

    def _mountExists(self, resource, mount=None):
        mounts = open("/proc/mounts", "r").readlines()
        for entry in mounts:
            entryResource, entryMount, entryType, options, freq, passno = entry.split()
            if (mount == entryMount or mount == None) and resource == entryResource:
                return True

        return False

    def testLowLevelAPI(self):
        dir = tempfile.mkdtemp()
        for i in range(10):
            nfs.mount(self.mycfg["NfsMount1"], dir)
            self.assertTrue(self._mountExists(self.mycfg["NfsMount1"], dir))
            nfs.umount(self.mycfg["NfsMount1"], dir)
            self.assertFalse(self._mountExists(self.mycfg["NfsMount1"], dir))

    def testHighLevelAPI(self):
        dir = tempfile.mkdtemp()
        connection = StorageServerConnection()
        connection.storage_repository = dir
        for i in range(10):
            statusList = connection.connect(1, 0, [{"id" : 1, "connection" : self.mycfg["NfsMount1"]}])
            self.assertTrue(self._mountExists(self.mycfg["NfsMount1"]))
            statusList = connection.disconnect(1, 0, [{"id" : 1, "connection" : self.mycfg["NfsMount1"]}])
            self.assertFalse(self._mountExists(self.mycfg["NfsMount1"]))

def suite():
    tests = {
        NfsMountingRace : ["testLowLevelAPI", "testHighLevelAPI"]
    }

    resSuite = ut.TestSuite()
    for testcase, methods in tests.iteritems():
        resSuite.addTests(map(testcase, methods))

    return resSuite

validateConfig = lambda cfg : vdst.validateSuiteConfig(suite(), cfg)
